export class UniRequest {
  private config: HttpUniConfig;
  public interceptors: Interceptors;
  private caches = new Map<string, CacheItem>();
  private pendingRequests = new Map<string, UniApp.RequestTask>();

  constructor(config: HttpUniConfig) {
    this.config = {
      timeout: 10000, // 默认超时时间10秒
      ...config,
    };
    this.interceptors = {
      requestInterceptor: null,
      responseInterceptor: null,
      errorInterceptor: null,
    };
  }
  //   生成缓存key
  private generateCacheKey(config: RequestConfig): string {
    if (config.cacheKey) return config.cacheKey;
    const { url, data, method = 'GET' } = config;
    return `${method}_${url}_${JSON.stringify(data || {})}`;
  }

  // 设置缓存
  private setCache(key: string, data: any, expire?: number): void {
    this.caches.set(key, {
      data,
      timestamp: Date.now(),
      expire: expire || 0,
    });
  }

  private async request<T = any>(options: RequestConfig): Promise<T> {
    try {
      // 检查缓存 有缓存直接返回结果
      if (options.cacheTime) {
        const cacheKey = this.generateCacheKey(options);
        const cachedItem = this.caches.get(cacheKey);
        if (cachedItem && Date.now() < cachedItem.timestamp + (cachedItem?.expire || 0)) {
          return cachedItem.data as T;
        }
      }
      let config = { ...options };
      // 处理请求拦截器
      if (this.interceptors.requestInterceptor) {
        config = await this.interceptors.requestInterceptor(config);
      }

      // 合并配置
      const finalConfig: RequestConfig = {
        timeout: this.config.timeout,
        ...config,
        url: config.url.startsWith('http') ? config.url : `${this.config.baseurl || ''}${config.url}`,
      };

      // 存储请求任务以便取消
      const requestKey = this.generateCacheKey(finalConfig);

      const response = await new Promise((reslove, reject) => {
        const requestTask = uni.request({
          ...finalConfig,
          success: (res) => {
            reslove(res);
          },
          fail: (err) => {
            reject(err);
          },
          complete: () => {
            this.pendingRequests.delete(requestKey);
          },
        });
        this.pendingRequests.set(requestKey, requestTask);
      });
      let responseData = response;
      if (this.interceptors.responseInterceptor) {
        responseData = await this.interceptors.responseInterceptor(response as UniNamespace.RequestSuccessCallbackResult);
      }
      // 缓存
      if (options.cacheTime) {
        const cacheKey = options.cacheKey || requestKey;
        this.setCache(cacheKey, responseData as T, options.cacheTime);
      }
      return responseData as T;
    } catch (error) {
      if (this.interceptors.errorInterceptor) {
        return await this.interceptors.errorInterceptor(error);
      }
      throw error;
    }
  }

  //   发送请求
  get<T = any>(url: string, data?: UniNamespace.RequestOptions['data'], config?: Omit<RequestConfig, 'url' | 'method'>, cacheTime?: number) {
    return this.request<T>({ url, method: 'GET', ...config, data, cacheTime });
  }
  // 发送请求
  post<T = any>(url: string, data?: UniNamespace.RequestOptions['data'], config?: Omit<RequestConfig, 'url' | 'method'>, cacheTime?: number) {
    return this.request<T>({ url, method: 'POST', ...config, data, cacheTime });
  }
}
// 示例
const api = new UniRequest({
  baseurl: 'https://api.example.com',
});

api.interceptors.responseInterceptor = (response) => {
  return response.data;
};

export const login = () =>
  api.get<number>('http://demo.ip-api.com/json/?fields=66842623&lang=en', '', {
    header: {
      'Content-Type': 'application/json',
    },
  });
